package advertising

import (
	"encoding/json"
	"gitee.com/alex_li/amazon-rpt/internal/rest"
	"gitee.com/alex_li/amazon-rpt/internal/sdk/dict"
	"github.com/lishimeng/go-log"
	"io"
)

type ErrorInfo struct {
	Code    string `json:"code,omitempty"`
	Detail  string `json:"detail,omitempty"`
	Message string `json:"message,omitempty"`
}

type DateDuration struct {
	StartDate string `json:"startDate"` // yyyy-mm-dd
	EndDate   string `json:"endDate"`   // yyyy-mm-dd
}

type RptFilter struct {
	Field  string   `json:"field"`
	Values []string `json:"values"`
}

type RptConfig struct {
	AdProduct    string            `json:"adProduct,omitempty"`
	GroupBy      []string          `json:"groupBy,omitempty"`
	Columns      []string          `json:"columns,omitempty"`
	ReportTypeId dict.ReportTypeId `json:"reportTypeId,omitempty"`
	TimeUnit     string            `json:"timeUnit,omitempty"`
	Format       string            `json:"format,omitempty"`
	Filters      []RptFilter       `json:"filters,omitempty"`
}

type RptHeader struct {
	Name string `json:"name"`
	DateDuration
}

type RptStatus struct {
	ReportId      string `json:"reportId,omitempty"`
	Name          string `json:"name,omitempty"`
	Status        string `json:"status,omitempty"`
	FailureReason string `json:"failureReason,omitempty"`

	CreatedAt   string `json:"createdAt,omitempty"`
	UpdatedAt   string `json:"updatedAt,omitempty"`
	GeneratedAt string `json:"generatedAt,omitempty"`

	FileSize     int64  `json:"fileSize,omitempty"`
	Url          string `json:"url,omitempty"`
	UrlExpiresAt string `json:"urlExpiresAt,omitempty"`
	DateDuration
	ErrorInfo
}

type RptReq struct {
	RptHeader
	Config RptConfig `json:"configuration,omitempty"`
}

const (
	AmazonReportContentType = "application/vnd.createasyncreportrequest.v3+json"
)

func (c *Client) CreateReport(req RptReq) (resp RptStatus, err error) {
	var action = "/reporting/reports"
	request, err := c.request()
	if err != nil {
		log.Info(err)
		return
	}
	err = request.Path(action).
		Accept(rest.ApplicationJson).
		Body(req).
		Response(&resp).
		Json(rest.POST, AmazonReportContentType)
	if err != nil {
		log.Info(err)
		return
	}
	return
}

func (c *Client) ReportStatus(id string) (resp RptStatus, err error) {
	var action = "/reporting/reports"
	req, err := c.request()
	if err != nil {
		log.Info(err)
		return
	}
	err = req.Path(action).Path(id).
		Accept(rest.ApplicationJson).
		Response(&resp).
		Json(rest.GET, AmazonReportContentType)
	if err != nil {
		log.Info(err)
		return
	}
	bs, _ := json.Marshal(resp)
	log.Info(string(bs))
	log.Info("rtp_id: %s", resp.ReportId)
	log.Info("rpt_name: %s", resp.Name)
	log.Info("status: %s", resp.Status)
	return
}

func (c *Client) DownloadReport(url string, h func(size int64, reader io.Reader)) (err error) {
	err = rest.NewRequest(url, c.ssl).Download(h)
	return
}
